// 云函数 updateTest/index.js
'use strict';
exports.main = async (event, context) => {
	
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}
	
  // 尽快返回结果，不等待事件循环清空
  context.callbackWaitsForEmptyEventLoop = false;
  console.log("updateTest invoked with event:", body);

  const { userId } = body;
  if (!userId) {
    return { code: 1, message: '缺少用户ID' };
  }
  
  const db = uniCloud.database();
  const collection = db.collection('uni-id-users');
  
  try {
    // 查询当前用户数据
    const userRes = await collection.doc(userId).get();
    console.log("用户查询结果:", userRes);
    
    if (!userRes.data || userRes.data.length === 0) {
      return { code: 1, message: '用户不存在' };
    }
    
    // 获取当前测试次数，默认为 0
    const currentFrequency = userRes.data[0].test_frequency || 0;
    const newFrequency = currentFrequency + 1;
    console.log("当前测试次数:", currentFrequency, "更新后测试次数:", newFrequency);
    
    // 更新用户测试次数
    const updateRes = await collection.doc(userId).update({
      test_frequency: newFrequency
    });
    console.log("更新结果:", updateRes);
    
    return { code: 0, message: '更新成功', data: updateRes };
  } catch (error) {
    console.error("updateTest 出现错误:", error);
    return { code: 1, message: '更新失败: ' + error.message };
  }
};
